package com.ete.service.util

import android.util.Log
import com.ete.service.service.log.Shell
import com.ete.service.service.log.UploadLogUtil
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

/**
 * 上传系统日志工具类
 * @author chenxiaojin
 * @date 2024/5/21
 */
object SystemLogUtil {

    private const val TAG = "SystemLogUtil"
    private val dateFormat = SimpleDateFormat("yyyy_MM_dd")
    private const val LOG_FILTER = "'^(?!.*(errlog.umeng.com)).*'"

    // 过滤日志时间格式
    private val filterLogDateFormat = SimpleDateFormat("MM-dd HH:mm:ss.SSS", Locale.US)

    // 日志抓取往前偏移时间，2分钟， 即抓取闪退前5分钟的日志记录
    private const val OFFSET_TIME = 2 * 60 * 1000

    val shell by lazy { Shell("sh") }

    @JvmStatic
    fun createSystemLog(mWriterDir: String): Boolean {
        try {
            val date = dateFormat.format(Date())
            val dir = File(mWriterDir)
            if (!dir.exists()) {
                dir.mkdirs()
            }
            // 切换到root, 否则无法打印系统日志
            var result = shell.run("su")
            if (result.isSuccess) {
                Log.i(TAG, "Prepare Write system log (su) success.")
            } else {
                Log.i(TAG, "Prepare Write system log (su) failed. Error:${result.stderr()}")
            }
            val file = "${mWriterDir}/system_${date}.log"
            result = shell.run("logcat -t 20000000 >> $file")
            if (result.isSuccess) {
                Log.i(TAG, "Write system log to $file success.")
                Log.i(TAG, "Start upload system log.")
            } else {
                Log.i(TAG, "Write system log failed. Error:${result.stderr()}")
            }
            return result.isSuccess
        } catch (e: Exception) {
            Log.e(TAG, "Write system log to upload failed.Error:${e.message}")
            e.printStackTrace()
        }
        return false
    }
}